package com.ocr.adapter;

import java.util.List;

import com.ocr.MainActivity;
import com.ocr.R;
import com.ocr.dao.SettingDao;
import com.ocr.entities.Language;
import com.ocr.entities.LanguageContext;
import com.ocr.entities.SettingItem;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

public class LanguageAdapter extends ArrayAdapter<Language> {
	private List<Language> list;
	private int resId;
	private Context context;

	public LanguageAdapter(Context context, int textViewResourceId,
			List<Language> objects) {
		super(context, textViewResourceId, objects);
		// TODO Auto-generated constructor stub
		this.context = context;
		this.list = objects;
		this.resId = textViewResourceId;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(resId, null);
		}
		TextView txtLanguageName = (TextView) convertView
				.findViewById(R.id.txt_language_name);
		CheckBox chbSelected = (CheckBox) convertView
				.findViewById(R.id.chb_selected);
		Language language = list.get(position);
		Language selectedLanguage = LanguageContext.getListLanguages().get(
				MainActivity.SETTINGITEM.getSelectedLanguagePos());
		// action
		if (language.getLanguageCode().equals(
				selectedLanguage.getLanguageCode()))
			chbSelected.setChecked(true);
		else
			chbSelected.setChecked(false);
		chbSelected.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MainActivity.SETTINGITEM.setSelectedLanguagePos(position);
				MainActivity.SETTINGDAO.saveSetting(MainActivity.SETTINGITEM);
				notifyDataSetChanged();
			}
		});
		txtLanguageName.setText(language.getName());

		return convertView;
	}
}
